package top.huhuiyu.study.servlet.user;

import top.huhuiyu.study.dao.TbUserDAO;
import top.huhuiyu.study.entity.Result;
import top.huhuiyu.study.entity.TbUser;
import top.huhuiyu.study.util.JsonUtils;
import top.huhuiyu.study.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "RegServlet", urlPatterns = "/user/reg.action")
public class RegServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        resp.setContentType("application/json");
        try {
            // 获取前端递交的参数
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String userinfo = req.getParameter("userinfo");
            // 参数非空校验
            if (StringUtil.isBlank(username)) {
                Result<String> result = Result.fail("用户名不能为空", null);
                writer.println(JsonUtils.stringify(result));
                return;
            }
            if (StringUtil.isBlank(password)) {
                Result<String> result = Result.fail("密码不能为空", null);
                writer.println(JsonUtils.stringify(result));
                return;
            }
            if (StringUtil.isBlank(userinfo)) {
                Result<String> result = Result.fail("用户简介不能为空", null);
                writer.println(JsonUtils.stringify(result));
                return;
            }
            // 校验用户名是否存在
            TbUser check = TbUserDAO.queryByName(username);
            if (check != null) {
                Result<String> result = Result.fail("用户名已存在", null);
                writer.println(JsonUtils.stringify(result));
                return;
            }

            // 注册（添加用户信息）
            TbUser user = new TbUser();
            user.setUsername(username);
            user.setPassword(password);
            user.setUserinfo(userinfo);
            int i = TbUserDAO.reg(user);
            if (i == 1) {
                Result<String> result = Result.success("注册成功", null);
                writer.println(JsonUtils.stringify(result));
            } else {
                Result<String> result = Result.fail("注册失败", null);
                writer.println(JsonUtils.stringify(result));
            }


        } catch (Exception e) {
            e.printStackTrace();
            Result<String> result = Result.fail("注册发生错误", null);
            writer.println(JsonUtils.stringify(result));
        }
    }
}
